#pragma once

#include <cstring>
#include <sys/epoll.h>
#include "logtxt.hpp"

extern Log lg;
class epoller
{
    static const int size = 128;

private:
    int _epfd;
    int timeout = 2000;

public:
    epoller()
    {
        _epfd = epoll_create(size);
        if (_epfd < 0)
        {
            lg(Error, "creat epoll fail,strerror:%s", strerror(errno));
        }
        else
        {
            lg(Info, "creat epoll sucess,_epfd:%d", _epfd);
        }
    }
    int EpollerWait(struct epoll_event revs[], int max)
    {
        int n = epoll_wait(_epfd, revs, max, timeout); // 将就绪好的文件描述符放入revs，并且输出出去，每次最多带出max个
        return n;
    }
    int Epollerupdate(int oper, int sockfd, uint32_t _events)
    {
        int n = 0;
        if (_events == EPOLL_CTL_DEL)
        {
            n = epoll_ctl(_epfd, oper, sockfd, nullptr);
            if (n < 0)
            {
                lg(Error, "epoll_ctl delete error!");
            }
        }
        else
        {
            struct epoll_event event;
            event.events = _events;
            event.data.fd = sockfd; // 方便后期告诉我们是那一个fd就绪了

            n = epoll_ctl(_epfd, oper, sockfd, &event);
            if (n < 0)
            {
                lg(Error, "epoll_ctl error!");
            }
        }
        return n;
    }
    ~epoller()
    {
        close(_epfd);
    }
};
